// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../group/qqmap-wx-jssdk');
// 实例化API核心类
var qqmapsdk ;
Page({
  data: {
    nearbyCommunities: [],
    location:{},
    currentLocation: "暂无选择位置，请您选择拼团点",
    userId: null,
  },
  getLocationInfo(){
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'RJ6BZ-SHDKW-OCDR3-YRCRE-CL2VQ-Z4BST'
    });
    const latitude = this.data.location.latitude
    const longitude = this.data.location.longitude
    const location = {
      latitude: this.data.location.latitude,
      longitude: this.data.location.longitude
    };
    qqmapsdk.search({
      keyword: '社区',
      location: location,
      success: function (res) {
        console.log("qqMap:",res.data);
        wx.request({
          url: `http://localhost:9301/community/findCommunityInfo`,
          method:"POST",
          data:{
            nearbyCommunities : res.data
          },
          success: (res)=>{
            this.setData({
              nearbyCommunities: res.data.data
            })
            console.log(res);
          }
        })
        // this.setData({
        //   nearbyCommunities: res.data
        // })
      }.bind(this),
      fail: function (err) {
        console.log('请求失败', err);
      },
    })
    
  },
  onLoad(options) {
    wx.getStorage({
      key: "userInfo",
      success: function (res) {
        if (res.data) {
          this.setData({
            userId: res.data.id
          });
        }
      }.bind(this)
    }),
    this.getLocation()
  },

  getLocation() {
    wx.chooseLocation({
      success: (res)=>{
        this.setData({
          currentLocation: res.address,
          "location.latitude": res.latitude,
          "location.longitude": res.longitude,
        }, () => {
          // 位置更新后，重新获取周边社区信息
          this.getLocationInfo();
        });
      }
    })
  },
  handleAddCommunity(e){
    const title = e.currentTarget.dataset.title
    const address = e.currentTarget.dataset.address
    const lat = e.currentTarget.dataset.lat
    const lng = e.currentTarget.dataset.lng
    const qqMapId = e.currentTarget.dataset.id
    wx.request({
      url: `http://localhost:9301/user/joinCommunity`,
      method:"POST",
      data:{
        userId: this.data.userId,
        qqMapId: qqMapId,
        title: title,
        address: address,
        lat: lat,
        lng: lng,
      },
      success: (res)=>{
        console.log(res);
        wx.switchTab({
          url: '/pages/index/index',
        })
      }
    })
  },
});